from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, ForeignKey, Index
from sqlalchemy.orm import relationship
from backend.infrastructure.database import db


class SocialShare(db.Model):
    """社交分享记录表"""
    __tablename__ = 'social_shares'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='分享用户ID')
    student_id = Column(Integer, ForeignKey('students.id'), nullable=True, comment='关联学生ID')
    title = Column(String(200), nullable=False, comment='分享标题')
    content = Column(Text, nullable=False, comment='分享内容')
    images = Column(Text, nullable=True, comment='图片URL列表，JSON格式')
    share_type = Column(String(50), nullable=False, default='intervention', comment='分享类型：intervention-干预分享,experience-经验分享,question-问题咨询')
    tags = Column(String(500), nullable=True, comment='标签，逗号分隔')
    view_count = Column(Integer, default=0, comment='浏览次数')
    like_count = Column(Integer, default=0, comment='点赞数')
    comment_count = Column(Integer, default=0, comment='评论数')
    share_count = Column(Integer, default=0, comment='分享数')
    status = Column(String(20), default='active', comment='状态：active-正常,pending-审核中,rejected-已拒绝,deleted-已删除')
    audit_reason = Column(String(500), nullable=True, comment='审核拒绝原因')
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    user = relationship("User", back_populates="social_shares")
    student = relationship("Student", back_populates="social_shares")
    likes = relationship("SocialShareLike", back_populates="share", cascade="all, delete-orphan")
    comments = relationship("SocialShareComment", back_populates="share", cascade="all, delete-orphan")
    
    def to_dict(self):
        """转换为字典"""
        # 解析 images 字段（可能是JSON字符串或已是JSON数组）
        parsed_images = None
        if self.images:
            try:
                import json
                if isinstance(self.images, str):
                    parsed_images = json.loads(self.images)
                else:
                    parsed_images = self.images
            except Exception:
                parsed_images = [self.images] if isinstance(self.images, str) else None
        return {
            'id': self.id,
            'user_id': self.user_id,
            'student_id': self.student_id,
            'title': self.title,
            'content': self.content,
            'images': parsed_images,
            'share_type': self.share_type,
            'tags': self.tags,
            'view_count': self.view_count,
            'like_count': self.like_count,
            'comment_count': self.comment_count,
            'share_count': self.share_count,
            'status': self.status,
            'audit_reason': self.audit_reason,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'user_info': ({
                'id': self.user.id,
                'nickname': self.user.nickname,
                'avatar': self.user.avatar,
                'avatar_url': self.user.avatar  # 前端有的使用 avatar_url
            } if self.user else None),
            'student_info': {
                'id': self.student.id,
                'name': self.student.name,
                'school': self.student.school
            } if self.student else None
        }


class SocialShareLike(db.Model):
    """分享点赞记录表"""
    __tablename__ = 'social_share_likes'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    share_id = Column(Integer, ForeignKey('social_shares.id'), nullable=False, comment='分享ID')
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='点赞用户ID')
    created_at = Column(DateTime, default=datetime.now, comment='点赞时间')
    
    # 关联关系
    share = relationship("SocialShare", back_populates="likes")
    user = relationship("User")
    
    # 唯一约束：一个用户只能对同一分享点赞一次
    __table_args__ = (
        Index('idx_share_user_unique', 'share_id', 'user_id', unique=True),
    )
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'share_id': self.share_id,
            'user_id': self.user_id,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'user_info': {
                'id': self.user.id,
                'nickname': self.user.nickname,
                'avatar': self.user.avatar
            } if self.user else None
        }


class SocialShareComment(db.Model):
    """分享评论记录表"""
    __tablename__ = 'social_share_comments'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    share_id = Column(Integer, ForeignKey('social_shares.id'), nullable=False, comment='分享ID')
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='评论用户ID')
    parent_id = Column(Integer, ForeignKey('social_share_comments.id'), nullable=True, comment='父评论ID，用于回复功能')
    content = Column(Text, nullable=False, comment='评论内容')
    like_count = Column(Integer, default=0, comment='评论点赞数')
    status = Column(String(20), default='active', comment='状态：active-正常,deleted-已删除')
    created_at = Column(DateTime, default=datetime.now, comment='评论时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    share = relationship("SocialShare", back_populates="comments")
    user = relationship("User")
    parent = relationship("SocialShareComment", remote_side=[id])
    replies = relationship("SocialShareComment", back_populates="parent")
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'share_id': self.share_id,
            'user_id': self.user_id,
            'parent_id': self.parent_id,
            'content': self.content,
            'like_count': self.like_count,
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'user_info': {
                'id': self.user.id,
                'nickname': self.user.nickname,
                'avatar': self.user.avatar
            } if self.user else None,
            'replies': [reply.to_dict() for reply in self.replies if reply.status == 'active']
        }


class UserFollow(db.Model):
    """用户关注关系表"""
    __tablename__ = 'user_follows'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    follower_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='关注者ID')
    following_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='被关注者ID')
    created_at = Column(DateTime, default=datetime.now, comment='关注时间')
    
    # 关联关系
    follower = relationship("User", foreign_keys=[follower_id])
    following = relationship("User", foreign_keys=[following_id])
    
    # 唯一约束：一个用户只能关注另一个用户一次
    __table_args__ = (
        Index('idx_follower_following_unique', 'follower_id', 'following_id', unique=True),
    )
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'follower_id': self.follower_id,
            'following_id': self.following_id,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'follower_info': {
                'id': self.follower.id,
                'nickname': self.follower.nickname,
                'avatar': self.follower.avatar
            } if self.follower else None,
            'following_info': {
                'id': self.following.id,
                'nickname': self.following.nickname,
                'avatar': self.following.avatar
            } if self.following else None
        }


class ContentReport(db.Model):
    """内容举报记录表"""
    __tablename__ = 'content_reports'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    reporter_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='举报者ID')
    content_type = Column(String(50), nullable=False, comment='内容类型：share-分享,comment-评论')
    content_id = Column(Integer, nullable=False, comment='内容ID')
    report_reason = Column(String(200), nullable=False, comment='举报原因')
    report_detail = Column(Text, nullable=True, comment='举报详情')
    status = Column(String(20), default='pending', comment='状态：pending-待处理,processed-已处理,rejected-已驳回')
    admin_remark = Column(Text, nullable=True, comment='管理员备注')
    created_at = Column(DateTime, default=datetime.now, comment='举报时间')
    processed_at = Column(DateTime, nullable=True, comment='处理时间')
    
    # 关联关系
    reporter = relationship("User")
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'reporter_id': self.reporter_id,
            'content_type': self.content_type,
            'content_id': self.content_id,
            'report_reason': self.report_reason,
            'report_detail': self.report_detail,
            'status': self.status,
            'admin_remark': self.admin_remark,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'processed_at': self.processed_at.isoformat() if self.processed_at else None,
            'reporter_info': {
                'id': self.reporter.id,
                'nickname': self.reporter.nickname,
                'avatar': self.reporter.avatar
            } if self.reporter else None
        } 